import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import useUserStore from './stores/user';

NProgress.configure({ showSpinner: false });

const blackList = ['/personal' , '/cart','/order']

// 路由加载前
router.beforeEach(async (to, from, next) => { 
  const userStore = useUserStore()
    
  
    // 在显示进度条
    NProgress.start()

    const token = userStore.token
    // 判断是否有token
    if(token){
      if(to.path === '/phoneLogin'){
        next({path : '/'})
        NProgress.done()
      }else {
        const isLogin = !!userStore.userInfo.name
        if(isLogin){
          next()
        }else {
          try {
            await userStore.getUserInfo()
            next(to)
            NProgress.done()
          } catch (error) {
            await userStore.logout()
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          }
        }
      }
    }else {
      if(blackList.includes(to.path)){
        
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }else {
        next()
      }
    }
})

// 路由加载后
router.afterEach(() => {
	NProgress.done();
})
